package com.x86.interceptors;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.x86.util.JwtUtil;
import com.x86.util.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 用户操作拦截器
 * @author 风亦未止
 * @date 2021/11/20 21:09
 */
@Slf4j
public class InterceptorDo implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = null;
        String error = JSONUtil.toJsonStr(new ResponseResult<>(401,"token失效或未登录!",null));
        String token = request.getHeader("Token");
        DecodedJWT verify = null;
        try {
            verify = JwtUtil.verify(token);
        } catch (Exception e) {
            writer=response.getWriter();
            writer.print(error);
            writer.close();
            log.info("Token:"+token+" 无效~");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
